package com.iwop.moto.controller;

import com.alibaba.fastjson.JSON;
import com.iwop.moto.auth.LoginAuth;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.service.AuditHistoryService;
import com.iwop.moto.service.StoreService;
import com.iwop.moto.service.UserService;
import com.iwop.moto.service.YunxinService;
import com.iwop.moto.utils.api.YunXin.YunXinUtils;
import com.iwop.moto.utils.stringUtil.DateFormatter;
import com.iwop.moto.utils.stringUtil.DateUtils;
import com.iwop.moto.utils.stringUtil.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/*************************************************
 * 店铺
 * @author huyuangui on 2016/7/12.
 *************************************************/
@Controller
public class StoreController extends BaseController {
    @Autowired
    private StoreService storeService;
    @Autowired
    private AuditHistoryService auditHistoryService;
    @Autowired
    private UserService userService;

    @Autowired
    private YunxinService yunxinService;
    /***********************************************************************
     * 我要开店
     * @param request
     * @return
     ***********************************************************************/
    @RequestMapping("/api/store_setUpShop")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel setUpShop(HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        SuperRecordModel superRecordModel = this.getSRModel();
        try{
            boolean isCreate = "".equals(superRecordModel.getString("sid").trim());
            if(StringUtils.isEmpty(superRecordModel.getString("sid"))){
                superRecordModel.put("sid", UUID.randomUUID().toString());
            }
            superRecordModel.put("addtime", DateUtils.DateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
            superRecordModel.put("updatetime", DateUtils.DateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
            superRecordModel.put("address_up_time",new Date());
            superRecordModel.put("status","0");
            superRecordModel.put("scope","我要维修,上门拖车,预约维修,整车销售");
            superRecordModel.put("userId",getUserId());
            superRecordModel.put("storelevel",5);
            SuperRecordModel srmUserInfo = userService.findUserBySid(superRecordModel);
            SuperRecordModel result = storeService.save(superRecordModel);
            if(result==null){
                return  getErr(ErrCode.STORE_ERROR_SAVE);
            }
            if(srmUserInfo == null ){
                return getErr(ErrCode.STORE_ERROR_SAVE);
            }else{
                srmUserInfo.put("nickname",superRecordModel.get("realname"));
                srmUserInfo.put("province",superRecordModel.get("province"));
                srmUserInfo.put("city",superRecordModel.get("city"));
                srmUserInfo.put("area",superRecordModel.get("area"));
                srmUserInfo.put("town",superRecordModel.get("town"));
                srmUserInfo.put("address",superRecordModel.get("address"));
                srmUserInfo.put("audit_time",new Date());
                if(userService.findServiceCountByDistrict(srmUserInfo)==0){
                    srmUserInfo.put("audit_flag","1" );//没有服务商默认平台审核 获取 平台拒绝重新提交审核
                }else{
                    srmUserInfo.put("audit_flag","0" );//有服务商默认服务商审核
                }
                superRecordModel.put("auditFlag",srmUserInfo.getString("audit_flag"));
                userService.updateUser(srmUserInfo);
            }
            /** 审核历史记录 **/
            SuperRecordModel auditSrm = new SuperRecordModel();
            auditSrm.putAll(srmUserInfo);
            auditSrm.put("isCreate",isCreate);
            auditHistoryService.inserStoreAuditHistory(auditSrm);
        } catch (Exception e){
             e.printStackTrace();
        }
        resultModel.setData(JSON.toJSONString(superRecordModel));

        SuperRecordModel supers=new SuperRecordModel();
        supers.put("accid",getUserId());
            StringBuffer url = request.getRequestURL();
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
            supers.put("icon",tempContextUrl+superRecordModel.getString("storepath"));
            editIMUser(supers);

        return resultModel;
    }

    private boolean editIMUser(SuperRecordModel superRecordModel){
        try {
            SuperRecordModel srm=new SuperRecordModel();
            String result = YunXinUtils.updateIMUser(superRecordModel, srm);
            Map parse = (Map)JSON.parse(result);
            int code = (int)parse.get("code");
            if(code==200){
                yunxinService.updateIMUser(srm);
                return true;
            }else {
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断身份证是否重复
     * */
    @RequestMapping("/api/store/cardno")
    @ResponseBody
    public ResultModel existCardNo(){
     try {
         SuperRecordModel superRecordModel = this.getSRModel();
         SuperRecordModel cardno = storeService.findUserCard(superRecordModel.getString("cardno"));
         if (cardno!=null&& cardno.size()>0){
             return getErr(ErrCode.USER_CARD_ERROR);
         }else {
             return getSucceed(ErrCode.SUCCEED);
         }
     }catch (Exception e){
         e.printStackTrace();
         return getErr(ErrCode.USER_CARD_ERROR);
     }
    }

    /***********************************************************************
     * 根据店铺SID获取店铺信息
     * 参数
     * @param request
     * @return
     ***********************************************************************/
    @RequestMapping("/api/store_findStore")
    @ResponseBody
    //@LoginAuth(isval = true)
    public ResultModel findStore(HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        SuperRecordModel superRecordModel=this.getSRModel();
        if(StringUtils.isEmpty(superRecordModel.getString("sid"))){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return  resultModel;
        }
        superRecordModel =storeService.getStoreUserBySid(superRecordModel);
        if(superRecordModel==null){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_ISEXIST);
            return  resultModel;
        }
        return getSucceed(superRecordModel,ErrCode.SUCCEED);
    }

    /***********************************************************************
     * 根据用户id获取店铺详情
     * 参数 uid
     * @param request
     * @return
     ***********************************************************************/
    @RequestMapping("/api/store/detail")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel getStoreByUserId(HttpServletRequest request){
        try {
            SuperRecordModel storeByUserId =  userService.findUserAndStoreByUserId(getUserId()); //storeService.findStoreByUserId(superRecordModel);
            ResultModel resultModel=new ResultModel();
            if (storeByUserId!=null){
                String data = JSON.toJSONString(storeByUserId);
                resultModel.setData(data);
            }
            return resultModel;
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }
    /***********************************************************************
     * 修改
     * 店铺：user_id,storelevel,status 不能修改
     * @param request
     * @return
     ***********************************************************************/
    @RequestMapping("/api/store_saveStore")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel saveStore(HttpServletRequest request){
        ResultModel resultModel=new ResultModel();
        SuperRecordModel superRecordModel=this.getSRModel();
        superRecordModel.put("user_id",request.getParameter("session_id"));
        if(StringUtils.isEmpty(superRecordModel.getString("sid"))){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return  resultModel;
        }
        //只是更改相应的字段
        String keys=superRecordModel.getString("keys");
        SuperRecordModel tempSuperRecordModel=storeService.findById(superRecordModel);
        if(tempSuperRecordModel==null){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_ISEXIST);
            return  resultModel;
        }
 /*       if(keys.contains("tel1")){
            String updatetime=DateFormatter.simpleDateTimeFormat((Date)tempSuperRecordModel.get("updatetime"));
            if(updatetime!=null && updatetime.compareTo(DateUtils.DateToString(DateUtils.addMonth(new Date(),-3),"yyyy-MM-dd HH:mm:ss"))>0){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.STORE_ERROR_CHANGEONE);
                return  resultModel;
            }
        }*/
/*       if(keys.contains("address")){
            String addressUpTime= DateFormatter.simpleDateTimeFormat((Date) (tempSuperRecordModel.get("address_up_time")));
            if(addressUpTime!=null && addressUpTime.compareTo(DateUtils.DateToString(DateUtils.addMonth(new Date(),-3),"yyyy-MM-dd HH:mm:ss"))>0){
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.STORE_ERROR_CHANGEONE);
                return  resultModel;
            }
        }*/



        //不能修改字段user_id,storelevel,status
        if(keys.indexOf("user_id")>=0|| keys.indexOf("storelevel")>=0||keys.indexOf("status")>=0){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_FIELDSNOCHANGE);
            return  resultModel;
        }
        superRecordModel=copyModel(superRecordModel,tempSuperRecordModel,keys);
       // superRecordModel.put("updatetime",new Date());
        superRecordModel.put("address_up_time",new Date());
        superRecordModel= storeService.save(superRecordModel);
        if(superRecordModel==null){
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_ISEXIST);
            return  resultModel;
        }
        SuperRecordModel supers=new SuperRecordModel();
        supers.put("accid",getUserId());
        if (keys.equals("storepath")){
            StringBuffer url = request.getRequestURL();
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
            supers.put("icon",tempContextUrl+superRecordModel.getString("storepath"));
            editIMUser(supers);
        }
        if (keys.equals("storename")){
            supers.put("name",superRecordModel.getString("storename"));
            editIMUser(supers);
        }

        resultModel.setData(JSON.toJSONString(superRecordModel));
        return resultModel;
    }

    /**
     * 功能：修改未通过审核的店铺<br>
     * 测试：192.168.1.158:8888/api/store/update?sid=f02b510a-6dd0-4200-a49d-82647822192e&realname=测试<br>
     * 参数：sid：主键<br>
     * 参数：realname：真实姓名<br>
     * 参数：cardno：身份证号码<br>
     * 参数：frontpath：身份证正面<br>
     * 参数：sidepath：身份证反面<br>
     * 参数：operator：经营者<br>
     * 参数：regname：营业执照号<br>
     * 参数：certpath：营业执照图片<br>
     * 参数：storename：店铺名<br>
     * 参数：address：地址<br>
     * 参数：contacts：联系人<br>
     * 参数：tel1：联系电话1<br>
     * 参数：storepath：店铺照片<br>
     * 参数：addtime：修改时间<br>
     * @return
     * <p>
     *{"code":1,"mem":"","data":"\"成功\""}
     * </p>
     * */
    @RequestMapping("/api/store/update")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel StoreEditForNoPass(){
        SuperRecordModel SRModel=this.getSRModel();
        try {
            SuperRecordModel byId = storeService.findById(SRModel);
            SuperRecordModel srm=new SuperRecordModel();
            srm.put("userId",byId.getString("user_id"));
            SRModel.put("addtime",new Date());
            if (byId.getString("status").equals("-1")&&byId.getString("status").equals("-2")){
                SRModel.put("status","0");
                storeService.updateStoreByNoPass(SRModel);
                srm.put("auditFlag","0");
                userService.updateUserAuditStatus(srm);
                return getSucceed(ErrCode.SUCCEED);
            }else {
                return getErr(ErrCode.ERROR_SYSTEM);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


    @RequestMapping("/api/store/click")
    @ResponseBody
    public ResultModel updateStoreClick() {
        try {
            SuperRecordModel SRModel = this.getSRModel();
            storeService.updateStoreClick(SRModel);
            return getSucceed(ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * tel 电话号码
     * */
    @RequestMapping("/api/store/user_tel")
    @ResponseBody
    public ResultModel getStoreNameByTel() {
        try {
            SuperRecordModel SRModel = this.getSRModel();
            SRModel=storeService.getStoreNameByTel(SRModel);
            if(null==SRModel||SRModel.size()==0){
                return getErr(ErrCode.STORE_INFO_ERROR_ISEXIST);
            }
            return getSucceed(SRModel,ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 店铺搜索功能
     * @参数 name 店铺名称
     * */
    @RequestMapping("/api/find/store/name")
    @ResponseBody
    public ResultModel apiFindStoreName() {
        try {
            SuperRecordModel SRModel = this.getSRModel();
            List<SuperRecordModel> list=storeService.findStoreByStoreName(SRModel);
            return getSucceed(list,ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }
}
